package cn.cloudmenu.android;

import java.net.URI;

import org.json.JSONArray;
import org.json.JSONObject;

import android.webkit.WebView;

import cn.cloudmenu.android.activity.ChooseTable;

import com.strumsoft.websocket.phonegap.WebSocket;

public class TablesWebSocket extends WebSocket {
	private UserProfile user;
	private MenuCoverBean menu;
	private ChooseTable chooseTableActivity;
	public TablesWebSocket(WebView appView, URI uri, UserProfile user, MenuCoverBean menu, ChooseTable chooseTableActivity) {
		super(appView, uri, Draft.DRAFT76, user.getNickname());
		this.user = user;
		this.menu = menu;
		this.chooseTableActivity = chooseTableActivity;
	}

	
	public void onMessage(final String msg) {
		super.onMessage(msg);
		System.out.println("00000000000000000000000000000000TablesWebSocket onMessage() msg = " + msg);
		try{
			JSONObject json = new JSONObject(msg);
			if("openDone".equals(json.getString("command"))){
				MenuOpeningTableBean table = new MenuOpeningTableBean();
				table.setMenuId(menu.getId());
				table.setTableName(user.getNickname());
				table.setOpener(user.getNickname());
				chooseTableActivity.startMakingOrder(table);
			}else if("tableList".equals(json.getString("command"))){
				JSONArray tables = json.getJSONArray("tableList");
				for(int i=0; i<tables.length(); i++){
					JSONObject table = tables.getJSONObject(i);
					System.out.println("00000000000000000000000000000000TablesWebSocket onMessage() command tableList table = "+table);
				}
				this.chooseTableActivity.setTableList(tables);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	public void onOpen() {
		super.onOpen();
		System.out.println("00000000000000000000000000000000TablesWebSocket onOpen() ");
		tableList();
	}
	
	public void tableList(){
		try {
			JSONObject command = new JSONObject();
			command.put("command", "tableList");
			command.put("menuId", menu.getId());
			this.send(command.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	public void openTable(){
		System.out.println("00000000000000000000000000000000TablesWebSocket openTable() ");
		try {
			JSONObject command = new JSONObject();
			command.put("command", "openTable");
			command.put("menuId", menu.getId());
			command.put("menuName", menu.getName());
			command.put("tableName", user.getNickname());
			command.put("opener", user.getNickname());
			this.send(command.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onClose() {
		super.onClose();
		System.out.println("00000000000000000000000000000000TablesWebSocket onClose() ");
	}

	public void onError(final Throwable t) {
		super.onError(t);
		System.out.println("00000000000000000000000000000000TablesWebSocket onError() t.getMessage() = " + t.getMessage());
	}

}
